import {AfterViewInit, Component, OnInit, ViewChild} from '@angular/core';
import {API, MsgConstants} from '../../constants/constants';
import {TreeUtil} from '../../util/tree-util';
import {OneOperationComponent} from '../../widgets/one-operation/one-operation.component';
import {OneDialogService} from '../../widgets/one-dialog/one-dialog.service';
import {MsgResult} from '../../models/msg-result';
import {PageSubject} from '../../util/page-subject';
import {ResponseUtil} from '../../util/response-util';
import {ActivatedRoute, Router} from '@angular/router';
import {TableUtil} from '../../util/table-util';
import {RescatalogService} from './rescatalog.service';
import {Rescatalog} from './rescatalog';

declare var $;

@Component({
  selector: 'app-rescatalog',
  templateUrl: './rescatalog.component.html',
  styleUrls: ['./rescatalog.component.css']
})
export class RescatalogComponent implements OnInit, AfterViewInit {
  @ViewChild(OneOperationComponent) operation: OneOperationComponent;
  // 按钮点击触及事件
  proxy = {
    // 添加，修改，删除
    'resCatalogAdd': () => this.resCatalogAdd(),
    'resCatalogUpdate': () => this.resCatalogUpdate(),
    'resCatalogDelete': () => this.resCatalogDelete()
  };
  id: Array<string> = [];
  table;
  treeObj;
  resCatalog: Rescatalog;

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private tableUtil: TableUtil,
    private treeUtil: TreeUtil,
    private rescatalogService: RescatalogService,
    private pageSubject: PageSubject,
    private dialogService: OneDialogService,
    private responseUtil: ResponseUtil
  ) {

  }
  ngOnInit() {
    // 初始化面包屑导航
    this.pushPage();
    // 初始化表单
    this.loadDic();

    this.initResCaTree();
  }


  ngAfterViewInit() {
    // 操作函数代理
    this.operation.proxy = this.proxy;
  }

  /**
   * 面包屑导航
   */
  pushPage() {
    //  let path = new Path('资源目录', '');
    this.pageSubject.pushPage('资源目录', '查询');
  }

  search() {
    this.table.bootstrapTable('refresh');
  }

  loadDic() {
    this.table = this.tableUtil.load('one_table_rescatalog', {
      columns: [
        {checkbox: true },
        {field: 'id', title: 'ID', align: 'left', visible: false, switchable: false},
        {field: 'resCode', title: '编码', align: 'left'},
        {field: 'resValue', title: '值', align: 'right'},
        {field: 'resName', title: '名称', align: 'left'},
        {field: 'enName', title: '英文名称', align: 'left'},
        {field: 'ORDERNUM', title: '排序', align: 'right', sortName: 'ORDERNUM', sortable: true},
        {field: 'describe', title: '描述', align: 'left'},
        {field: 'isUse', title: '启用', align: 'left', formatter: this.yesOrNoFormat}
      ],
      idField: 'id',
      sidePagination: 'server',
      pagination: true,
      pageNumber: 1,
      pageSize: 15,
      pageList: [10, 25, 50, 100],
      paginationPreText: '上一页',
      paginationNextText: '下一页',
      paginationLoop: false, // 是否开启循环分页
      singleSelect: false, // 多选
      clickToSelect: true, // 点击选中
      toolbar: '#one_operation_rescatalog',
      url: API.rescatalogPageListV2,
      method: 'post',
      // 传递附加参数
      queryParams: (params) => {
        params.resCode = $('#resCatalogCode').val();
        params.resName = $('#resCatalogName').val();
        params.isUse = $('#isUse').val();
        params.pId =  $('#resCatalogId').val();
        return params;
      },
      // 返回数据处理器
      responseHandler: (result) => {
        return this.responseUtil.bsPageHandler(result, () => {
          result.data.rows.forEach(function (value) {
            value.ORDERNUM = value.orderNum || '';
          });
        });
      },
      height: 700, // table高度
      sortable: true,
      order: 'asc',
      sortName: 'ORDERNUM',
      //  search:true,// 是否显示搜索框
      //  searchOnEnterKey:true,// 点击enter键是否触发搜索事件
      //  searchText:'',// 默认搜索内容
      //  smartDisplay:true,// 智能显示分页或card视图
      showColumns: true, // 显示自定义显示列按钮
      showRefresh: true, // 显示刷新按钮
      minimumCountColumns: 3, // 最少保留显示的列数量
      showToggle: true, // 显示视图切换按钮
      showPaginationSwitch: true, // 显示是否分页切换按钮
      classes: 'table table-hover',
      striped: true, // 隔行变色
      mobileResponsive: true// 响应式
    });
    this.tableUtil.bindResetTableView(this.table);
  }

  /**
   * 初始化菜单树
   */
  initResCaTree() {
     this.rescatalogService.getRescatalog().subscribe(
       result => this.responseUtil.success(result, this.processMenuTreeResult),
       message => this.responseUtil.error(message)
     );
  }
  private processMenuTreeResult = (result: MsgResult) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      this.initResCaTreeObj(result.data);
    }
    if (result && result.code !== MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  };
  initResCaTreeObj(data) {
    // 初始化菜单树
    const setting = {
      callback: {
        onClick: this.clickTree
      },
      data: {
        key: {
          name: 'resName'
        }
      }
    };
    // 把树放进页面
    this.treeObj = $.fn.zTree.init($('#resCatalogManagerZTree'), setting, this.treeUtil.wrapToStandard(data));
  }

  clickTree = (event, treeId, treeNode) => {
    const pId = $('#resCatalogId');
    if (treeNode.id === pId.val()) {
      const selectedArray: Array<object> = this.treeObj.getSelectedNodes();
      if (selectedArray.length > 0) {
        this.treeObj.cancelSelectedNode(selectedArray[0]);
      }
      pId.val('');
    } else {
      pId.val(treeNode.id);
    }
    this.search();
  };

  /**
   * yesOrNo格式化函数
   * @param value
   * @param row
   * @param index
   * @returns {any}
   */
  private yesOrNoFormat(value, row, index) {
    if (value === '1') {
      return '是';
    }
    if (value === '0') {
      return '否';
    }
  }

  resCatalogAdd() {
    this.router.navigate(['add'], {relativeTo: this.route});
  }

  /**
   * 实现修改页面跳转
   */
  resCatalogUpdate() {
    const rows = this.table.bootstrapTable('getSelections');
    this.id = this.tableUtil.getCloumns(rows, 'id');
    if (this.id.length === 1) {
      this.router.navigate(['update', {id: this.id[0]}], {relativeTo: this.route});
    } else {
      this.dialogService.modalInfo('请选择一条数据');
    }
  }

  resCatalogDelete() {
    const rows = this.table.bootstrapTable('getSelections');
    this.id = this.tableUtil.getCloumns(rows, 'id');
    if ( undefined === this.id || this.id.length === 0 ) {
      this.dialogService.modalInfo('请选择一条数据');
    } else {
      this.dialogService.modalInfoWithCancelBtn('确定删除？', this.requestDelete);
    }
  }

  private requestDelete = () => {
     this.rescatalogService.deleteRescatalog(this.id.join(',')).subscribe(
       result => this.responseUtil.success(result, this.processDicDeleteResult),
       message => this.responseUtil.error(message)
     );
  };

  processDicDeleteResult = (result: MsgResult) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      this.search();
      this.initResCaTree();
    }
    if (result && result.code !== MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message, () => this.search());
    }
  }

}
